package info.johnwheeler.gaestorage.servlet;

import info.johnwheeler.gaestorage.core.Photo;
import info.johnwheeler.gaestorage.core.PhotoDao;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;



@SuppressWarnings("serial")
public class BlobstoreUploadServlet extends AbstractUploadServlet {
    private BlobstoreService blobService = BlobstoreServiceFactory.getBlobstoreService();
    private PhotoDao dao = new PhotoDao();

    @Override
    protected void showForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uploadUrl = blobService.createUploadUrl("/blobstore");
        req.setAttribute("uploadUrl", uploadUrl);
        req.getRequestDispatcher("blobstore.jsp").forward(req, resp);
    }

    @Override
    protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, BlobKey> blobs = blobService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get(blobs.keySet().iterator().next());

        String title = req.getParameter("title");
        String caption = req.getParameter("caption");
        String photoPath = blobKey.getKeyString();
        
        Photo photo = new Photo(title, caption);
        photo.setPhotoPath(photoPath);
        dao.save(photo);

        resp.sendRedirect("blobstore?action=display&id=" + photo.getId());
    }

    @Override
    protected void showRecord(long id, HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        Photo photo = dao.findById(id);
        String photoPath = photo.getPhotoPath();

        blobService.serve(new BlobKey(photoPath), resp);
    }
}
